package com.xpmusic.controller.consumer;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xpmusic.dao.impl.ConsumerDaoImpl;
import com.xpmusic.model.ConsumerInfo;
import com.xpmusic.model.RegisterFormBean;
import com.xpmusic.util.ServletUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@WebServlet("/userRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String inputStringInfo = ServletUtil.getInputStringInfo(request);
        System.out.println("UserRegisterServlet-json:" + inputStringInfo);
        /**
         * 验证验证码是否正确
         */
        JsonObject jsonObject = new JsonParser().parse(inputStringInfo).getAsJsonObject();
        JsonObject result = new JsonObject();
        if(!jsonObject.get("code").getAsString().equalsIgnoreCase(request.getSession().getAttribute("code").toString())){
            result.addProperty("code","false");
            response.getWriter().write(result.toString());
            return;
        }

        //解析用户注册发送的json数据
        Gson gson = new Gson();
        ConsumerInfo consumerInfo = gson.fromJson(inputStringInfo, ConsumerInfo.class);
        boolean b = new ConsumerDaoImpl().insertConsumerInfo(consumerInfo);
        if(b){
            request.getSession().setAttribute("loginName",jsonObject.get("loginName").getAsString());
            response.setContentType("text/json; charset=utf-8");
            result.addProperty("result","true");
            result.addProperty("url","success.jsp");
            response.getWriter().write(result.toString());
        }else {
            result.addProperty("result","false");
            response.getWriter().write(result.toString());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
